import { ref, reactive } from 'vue'
import { has } from 'lodash'
import { DEFAULT_ROW_KEY } from '@/constants/base.contant'

// 设置表格columns的默认属性
export const setColumns = (columns, resizable?) => {
  return columns.map(item => {
    let resizeAttr = {}
    if (resizable) {
      resizeAttr = {
        width: item.minWidth || item.width || 150,
        resizable: has(item, 'resizable') ? item.resizable : true
      }
    }
    return {
      ...item,
      ...resizeAttr,
      key: item.dataIndex,
      ellipsis: has(item, 'ellipsis') ? item.ellipsis : true
    }
  })
}

export const rowClassName = (_record, index) => (index % 2 === 1 ? 'table-striped' : null)

export const rowKey = DEFAULT_ROW_KEY

export const scrollConfig = { x: 1200 }

export const useTable = (getData, tableRowKey?) => {
  // 分页数据
  const pagination = reactive({
    total: 0,
    current: 1,
    pageSize: 10,
    showSizeChanger: true,
    showTotal: total => `共 ${total} 条`
  })

  const selectedRows = ref([])
  const rowKey = tableRowKey || DEFAULT_ROW_KEY

  const onSelectChange = selectedRowKeysList => {
    selectedRows.value = selectedRowKeysList
  }

  const rowSelection = {
    selectedRowKeys: selectedRows, //此处不能用selectedRows.value 因为是用到template里渲染的 不需要.value
    onChange: selectedRowKeysList => {
      selectedRows.value = selectedRowKeysList
    }
  }

  // 表格尺寸size拖动事件
  const handleResizeColumn = (w, col) => {
    col.width = w
  }

  // 分页切换
  const handlePageChange = ({ current, pageSize }) => {
    pagination.current = current
    pagination.pageSize = pageSize
    getData()
  }

  // 搜索事件
  const handleSearch = () => {
    pagination.current = 1
    getData()
  }

  return {
    rowKey,
    rowSelection,
    onSelectChange,
    selectedRows,
    pagination,
    scrollConfig,
    rowClassName,
    handleSearch,
    handlePageChange,
    handleResizeColumn
  }
}
